import config from '@/config.js';
import sign from "@/libs/net/sign.js";
import to from 'await-to-js';

const http = {
	async get(url, param, isShowLoading = "1") {
		let [err, res] = await to(http.request(url, param, isShowLoading, "get"));
		if (err) {
			return err;
		}
		return res;
	},
	async post(url, param, isShowLoading = "1") {
		let [err, res] = await to(http.request(url, param, isShowLoading, "post"));
		if (err) {
			return err;
		}
		return res;
	},
	async upload(url, filePath, param = {}, isShowLoading = "1") {
		let [err, res] = await to(http.uploadFile(url, filePath, param, isShowLoading));
		if (err) {
			return err;
		}
		return res;
	},

	uploadFile(url, filePath, param = {}, isShowLoading = "1") {
		if (isShowLoading) {
			uni.showLoading({
				title: '正在上传...'
			})
		}
		let combineObj = http.combimeData(param);
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: config.host + url,
				filePath: filePath,
				name: 'file',
				formData: combineObj.param,
				header: combineObj.header,
				success: (res) => {
					let result = res.data;
					if (typeof res.data == 'string') {
						result = JSON.parse(res.data);
					}
					resolve(result);
				},
				fail: (res) => {
					let result = res.data;
					if (typeof res.data == 'string') {
						result = JSON.parse(res.data);
					}
					reject(result);

				},
				complete() {
					uni.hideLoading();
				}
			});
		});

	},
	request(url, param, isShowLoading = "1", method = 'POST') {
		if (isShowLoading) {
			uni.showLoading({
				title: '正在加载...'
			})
		}
		let combineObj = http.combimeData(param);
		return new Promise((resolve, reject) => {
			uni.request({
				url: config.host + url,
				data: combineObj.param,
				method: method,
				header: combineObj.header,
				success(res) {
					//console.log(res);
					let code = parseInt(res.data.code);
					if (code === 0) { //找不到openid对应的用户
						resolve(res.data);
					} else if (code <= 99 && code >= 1) {
						uni.clearStorage();//清空本地缓存 
						//这里写未登录的逻辑
						uni.reLaunch({
							url: "/pages/index/index"
						})
						//reject(res.data);
					} else {
						reject(res.data);
					}
				},
				fail(err) {
					uni.hideLoading();
					reject(err);

				},
				complete() {
					uni.hideLoading();
				}
			});
		});
	},
	/**
	 * 组合header和bodydata参数
	 * @param {*} param 
	 * @returns 
	 */
	combimeData(param = {}) {
		let token = uni.getStorageSync("token");//从缓存取token
		let header = {};

		if (token) {
			header['token'] = token;
		}

		param = sign(param);
		return { param, header };
	}
}
export default http;